//
//  APIHSBCCities.m
//  Bracelet
//
//  Created by jing zhao on 3/12/15.
//  Copyright (c) 2015 jing zhao. All rights reserved.
//

#import "APIHSBCCities.h"
#import "FileReadAndWrite.h"
#define FILENAMECACHE_APIHSBCCITIES @"fileName_apiHsbcCities"

@implementation APIHSBCCities


-(instancetype)initCitiesData:(NSDictionary*)dic
{
    self= [super init];
    if (self) {
        
        int tempNum =[[dic objectForKey:APIKEYCITYNUM]intValue];
        self.strHtml = [dic objectForKey:APIKEYHTML];
        self.strCityNum = [NSString stringWithFormat:@"%d",tempNum];
        //如果使用cities info 可以将array里的dic 作为对象拆分
        self.arrayCitiesInfo = [dic objectForKey:APIKEYCITIESINFO];
        
    }
    return self;
}


+(instancetype)apiCitiesData:(NSDictionary*)dic
{
    return [[self alloc]initCitiesData:dic];
}
+(void)getHSBCDataSuccess:(void (^)(APIHSBCCities *mycity))successBlock
                  failure:(void (^)( NSError *error)) failureBlock
{
    NSString *strUserId = [[NSUserDefaults standardUserDefaults]objectForKey:USERID];
    NSDictionary *headerData =@{@"BasicAuthUsername":strUserId};
    
    [[APIConnection shareInstance]post:@"hbcn/hbcnCity" data:nil header:headerData netError:^(NSError *error) {
        failureBlock(error);
       
        //取缓存
        NSDictionary *dicCanch = [FileReadAndWrite getTheStorageDataWithFile:FILENAMECACHE_APIHSBCCITIES];
        if (dicCanch) {
            NSDictionary *dicSuccess = [dicCanch objectForKey:APIKEYData];
            successBlock([APIHSBCCities apiCitiesData:dicSuccess]);
        }
    } apiFinish:^(id data) {
        NSDictionary *dictionaryTemp = data;
        NSInteger codeTemp= [[dictionaryTemp objectForKey:APIKEYCODE]integerValue];
        if (codeTemp ==0) {
            NSDictionary *dicSuccess = [dictionaryTemp objectForKey:APIKEYData];
            successBlock([APIHSBCCities apiCitiesData:dicSuccess]);
            
            //存入缓存
            [FileReadAndWrite storageDataWithFile:FILENAMECACHE_APIHSBCCITIES andData:dictionaryTemp];
            
        }
        else
        {
            failureBlock(nil);
        }
    }];
}
@end
